import axios, { type AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import pinia from '@/stores/index';
import { useUserInfoStore } from '../stores/userInfo';


interface ResponseData<T> {
	code: number;
	data: T;
	message: string;
}


const service = axios.create({
	baseURL: '/api',
	timeout: 50000,
});

// 拦截器
service.interceptors.request.use(
	(config: any) => {
		if (useUserInfoStore().token) {
			config.headers['token'] = useUserInfoStore().token;
		}
		return config;
	}
);


service.interceptors.response.use(

	async (response: AxiosResponse<ResponseData<any>>) => {

		const res = response.data;
		if (res.code !== 20000 && res.code !== 200) {

			ElMessage({
				message: (typeof res.data == 'string' && res.data) || res.message || 'Error',
				type: 'error',
				duration: 5 * 1000
			})


			if (response.status === 401) {
				const storeUserInfo = useUserInfoStore(pinia)
				await storeUserInfo.reset()
				window.location.href = '/'
				ElMessageBox.alert('你已被登出，请重新登录', '提示', {})
					.then(() => { })
					.catch(() => { })
			}
			return Promise.reject(service.interceptors.response);
		} else {
			return res.data;
		}
	},
	(error) => {

		if (error.message.indexOf('timeout') != -1) {
			ElMessage.error('网络超时');
		} else if (error.message == 'Network Error') {
			ElMessage.error('网络连接错误');
		} else {
			if (error.response.data) ElMessage.error(error.response.statusText);
			else ElMessage.error('接口路径找不到');
		}
		return Promise.reject(error);
	}
);

export default service;
